package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.book.domain.LoginUser;
import com.book.entity.User;
import com.book.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    //根据邮箱判断是否数据库有这个人。数据库里面我把邮箱设置成了唯一索引
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getEmail, email);
        User user = userDao.selectOne(lqw);
        //如果没有查询到用户，用户就抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //把数据封装成UserDetails返回
        return new LoginUser(user);
    }
}
